package c.w.connection;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import c.w.constants.SystemConstants;

public class ConnBaseService {

	private NioSocketConnector connector = null;
	private IoSession session = null;
	private ConnectFuture connFuture = null;
	
	public boolean call() {

		int minimumConnectTimeout = 30000;
		int port = 2013;
		
		connector = new NioSocketConnector();
		
		//获取connector的过滤器控制权
		DefaultIoFilterChainBuilder chan = connector.getFilterChain();
		
		//过滤器
		ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory());
		
		chan.addLast("objFilter", filter);
		
		//handler里面的内容在什么时候被调用?
		connector.setHandler(new ConnBaseServiceHandler());
		
		// 设置超时检查时间间隔
		connector.setConnectTimeoutCheckInterval(minimumConnectTimeout);
		
		try{
		
			//根据主机名构建连接
//			final ConnectFuture cf = connector.connect(new InetSocketAddress(SystemConstants.SERVICE_HOST, port));
			connFuture = connector.connect(new InetSocketAddress(SystemConstants.SERVICE_HOST, port));
			
//			connFuture.awaitUninterruptibly();//等待,同步机制,它会将程序阻塞住，直到连接创建好，所以，当这行代码结束后，就可以直接获取session并执行write操作。
//			session = connFuture.getSession();
			
			connFuture.addListener(new IoFutureListener<ConnectFuture>() {
	
				//当mina连接成功时的回电函数,异步机制
				@Override
				public void operationComplete(ConnectFuture arg) {
					// TODO Auto-generated method stub
//					session = cf.getSession();
					session = arg.getSession();
					System.out.println("---1111111111-----连接成功,成功获得session--------" + session);
				}
			});
			
		} catch (Exception e) {
			// TODO: handle exception
			//客户端连接异常, 加入log文件最后发送给服务器
			return false;
		}
		
		return true;
	}
	
	public boolean close() {
		if (connector != null) {
			connector.dispose();
//			connector = null;
			if (this.session != null) {
				// 等待连接断开,1000是等待时间
				session.getCloseFuture().awaitUninterruptibly(1000);
//				session = null;
			} else {
				return false;
			}
		} else {
			return false;
		}
		
		return true;
	}
	
	/*public boolean connected() {
		if (session == null) {
			return false;
		}
		
		return true;
	}*/
	
	public void send(Object obj) {
		//连接服务器的等待时间,如果这个时间默认服务器连接失败, 超过这个时间自动重新连接服务器
		int backCallSeiverTime = 10 * 1000;
		//线程等待session返回
		long beginTime = System.currentTimeMillis();
		System.out.println("session is-----" + session);
		
		/*
		if (session == null) {
			connFuture.awaitUninterruptibly();
//			session = connFuture.getSession();
		}
		*/
		
		while(session == null){
			if (session != null) {
				if (!session.isClosing()) {
					return ;
				}
			}
			long endTime = System.currentTimeMillis();
			if (endTime - beginTime >= backCallSeiverTime) {
				System.out.println("重新连接");
				this.close();
				this.call();
				beginTime = System.currentTimeMillis();
			}
		}
		
		session.write(obj);
	}
	
	//设置session中每次都需要用到的内容: id
	public boolean setUsefulMessage(String key, Object message) {
		/*if (this.session == null) {
			return false;
		}*/
		System.out.println("设置session的属性");
		while(session == null){
			if (session != null) {
				if (!session.isClosing()) {
					
					System.out.println("session的属性设置成功");
					session.setAttribute(key, message);
					
					return true;
				}
			}
		}
		
		return true;
	}
}
